<template>
  <div class="panel-phone">
    <el-form
      ref="phoneFormRef"
      style="max-width: 600px"
      :model="phoneForm"
      :rules="rules"
      label-width="70px"
      size="large"
      class="phone-form"
      status-icon
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="phoneForm.phone" type="text" autocomplete="off" clearable />
      </el-form-item>
      <el-form-item label="验证码" prop="checkCode">
        <el-input v-model="phoneForm.checkCode" type="text" autocomplete="off" clearable />
        <count-down-btn
          :check-input="validPhoneInput"
          :send-request="sendRequest"
          :count-seconds="90"
          :width="'140px'"
          :init-tip="'发送验证码'"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import CountDownBtn from '@/base-ui/count-down-button/count-down-btn.vue';

const phoneFormRef = ref<FormInstance>();

const phoneForm = reactive({
  phone: '',
  checkCode: ''
});

const rules = {
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      pattern: /^(13[0-9]|14[579]|15[^4\D]|16[6]|17[0-8]|18[0-9]|19[89])\d{8}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ],
  checkCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      pattern: /^[0-9]{6}$/,
      message: '请输入6位数字验证码',
      trigger: 'blur'
    }
  ]
};

async function validPhoneInput() {
  let res: boolean = false;
  try {
    res = (await phoneFormRef.value?.validateField('phone', (err) => {
      console.warn(err);
    })) as boolean;
    if (!res) {
      ElMessage.error('手机号格式错误');
    }
  } catch (err) {
    console.warn(err);
    res = false;
  }
  return res;
}

async function sendRequest() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject();
    }, 3000);
  })
    .then((res) => {
      ElMessage.success('发送成功!');
      return res;
    })
    .catch((err) => {
      ElMessage.error('发送失败！验证码服务器暂不可用！');
      console.warn(err);
    });
}

function loginByPhone() {
  if (!phoneFormRef.value) return;
  phoneFormRef.value.validate((valid) => {
    if (valid) {
      // to do 调用store中的手机登录的方法
      ElMessage.warning('手机登录接口暂不可用！');
    } else {
      ElMessage.error('请填写正确的手机号和验证码');
      return false;
    }
  });
}

defineExpose({
  loginByPhone
});
</script>

<style scoped lang="scss">
.panel-phone {
  :deep(.el-form-item) {
    padding-right: 10px;

    .el-form-item__content {
      flex-wrap: nowrap;
      gap: 16px;
    }

    .el-button {
      width: 200px;
    }
  }

  .phone-form {
    margin-top: 20px;
  }
}
</style>
